package com.qf.commons.web.exception;

import com.qf.commons.core.exception.ServiceException;
import com.qf.commons.data.result.R;
import com.qf.commons.data.result.RCodes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常处理器
 * author Ken
 * create_time 2022/8/16
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public R serviceExceptioHandler(ServiceException e){
        return R.createFail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e){
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors = result.getAllErrors();
        List<String> errorInfo = new ArrayList<>();
        for (ObjectError error : errors) {
            errorInfo.add(error.getDefaultMessage());
        }
        return R.createFail(RCodes.DATA_CHEKCED_ERROR, errorInfo);
    }


    @ExceptionHandler
    public R globalExceptionHandler(Throwable t){
        //通过日志记录当前的异常信息
        log.error("全局异常被捕获！", t);
        return R.createFail(RCodes.FAIL);
    }
}
